#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>

#include "login.h"
void get_password(char *password,size_t size){
    struct termios oldt,newt;

    // 鑾峰彇褰撳墠缁堢璁剧疆
    tcgetattr(STDIN_FILENO,&oldt);
    newt=oldt;

    newt.c_lflag &= ~ECHO;

    tcsetattr(STDIN_FILENO,TCSANOW,&newt);

    printf("please input password:");
    fflush(stdout);

    fgets(password,size,stdin);

    tcsetattr(STDIN_FILENO,TCSANOW,&oldt);

    size_t len=strlen(password);

    if(len>0&&password[len-1]=='\n'){
        password[len-1]='\0';
    }

    printf("\n");
}

int login_handler(tlv_t *tlv,int sockfd,callback_ptr_t callback,void *args){
    char username[256]={0},password[256]={0},buffer[512]={0};

    puts("please input username:");
    if(fgets(username,sizeof(username),stdin)==NULL){
        return -1;
    }
    username[strcspn(username,"\n")]='\0';
    
    get_password(password,sizeof(password));
    
    size_t username_len=strlen(username);
    size_t password_len=strlen(password);
    size_t length=username_len+password_len+2;

    memcpy(buffer,username,username_len);
    buffer[username_len]=' ';
    memcpy(buffer+username_len+1,password,password_len);
    buffer[length-1]='\0';

    tlv_request(tlv,sockfd,REQUEST_CMD_LOGIN,length,(const uint8_t*)buffer,callback,args);
    return 0;
}
